 <template>
  <div>
    <Tabs
      :datas="tabConfig"
      v-model="selected"
      style="margin-bottom:20px"
    ></Tabs>
    <Form
      :label-width="110"
      :mode="mode"
      :model="form"
      :rules="validationRules"
      ref="form"
      :top="0.2"
      showErrorTip
    >
      <div v-show="selected == 'basic'">
        <FormItem label="文章名称" single prop="article_name">
          <input
            type="text"
            v-model="form.article_name"
            placeholder="输入文章名称"
            v-wordlimit="80"
          />
        </FormItem>

        <FormItem label="分类选择" prop="article_cate">
          <CategoryPicker
            ref="CategoryPicker"
            :option="cateOption"
            type="key"
            :showChildCount="true"
            v-model="form.article_cate"
          ></CategoryPicker>
        </FormItem>

        <FormItem label="选择标签" prop="article_label">
          <Select
            :deletable="selectDeletable"
            v-model="form.article_label"
            :datas="labelList"
            keyName="id"
            titleName="label_name"
            placeholder="选择标签"
          >
            <template slot="bottom">
              <div class="text-center">
                <Pagination
                  style=" margin-top:20px"
                  v-model="labelPagination"
                  align="center"
                  @change="labelCurrentChange"
                  small
                ></Pagination></div
            ></template>
          </Select>
        </FormItem>

        <FormItem
          label="文章首图"
          style="text-align:left"
          single
          prop="article_logo"
        >
          <button @click="showImageChecek" class="h-btn h-btn-green">
            选择图片
          </button>
          <Modal v-model="showDialog" :hasCloseIcon="true">
            <div style="width:700px;max-width:730px;min-width:700px;">
              <ImageCheck :isShowCheckBtn="true" @choose="chooseImg" />
            </div>
          </Modal>
          <div class="logoList" v-show="form.article_logo">
            <div class="logo">
              <img :src="form.article_logo" />
              <i @click="removeLogo" class="iconfont icon-shanchu  "></i>
            </div>
          </div>
        </FormItem>
        <FormItem label="简介" single prop="article_introduce">
          <textarea
            rows="3"
            v-autosize
            v-wordcount="50"
            v-model="form.article_introduce"
          ></textarea>
        </FormItem>
      </div>

      <div v-show="selected == 'seo'">
        <FormItem label="SEO标题" single prop="seo_title">
          <textarea
            rows="3"
            v-autosize
            v-wordcount="80"
            v-model="form.seo_title"
          ></textarea>
        </FormItem>
        <FormItem label="SEO关键字" single prop="seo_keywords">
          <textarea
            rows="3"
            v-autosize
            v-wordcount="100"
            v-model="form.seo_keywords"
          ></textarea>
        </FormItem>
        <FormItem label="SEO描述" single prop="seo_desc">
          <textarea
            rows="3"
            cols="4"
            v-autosize
            v-wordcount="200"
            v-model="form.seo_desc"
          ></textarea>
        </FormItem>
      </div>
      <div v-show="selected == 'detail'">
        <vue-ueditor-wrap
          :destroy="true"
          v-model="form.article_detail"
          :config="UeditorConfig"
          @beforeInit="addCustomButtom"
        ></vue-ueditor-wrap>
      </div>
      <FormItem :no-padding="true" single v-padding="30" class="text-center">
        <Button
          color="green"
          size="l"
          v-if="id"
          :loading="isLoading"
          @click="update"
          >更新</Button
        >
        <Button
          color="green"
          size="l"
          v-else
          :loading="isLoading"
          @click="submit"
          >添加</Button
        >
      </FormItem>
    </Form>
  </div>
</template>
<script>
import VueUeditorWrap from "vue-ueditor-wrap";
import ImageCheck from "@/components/ImageCheck/index.vue";
export default {
  name: "artilceCreate",
  components: { ImageCheck, VueUeditorWrap },
  props: ["id"],
  //编辑时传入的ID
  data() {
    return {
      UeditorConfig: {
        serverUrl: "",
        UEDITOR_HOME_URL: "/editor/"
      },
      selectDeletable: true,
      labelList: [],
      cateOption: {
        keyName: "id",
        titleName: "cate_name",
        parentName: "cate_parent",
        childrenName: "children",
        dataMode: "tree",
        datas: []
      },
      labelPagination: {
        page: 1,
        size: 6,
        total: 0
      },
      showDialog: false,
      editor: null,
      editorData: "",
      // 编辑器
      tabConfig: {
        basic: "基本设置",
        seo: "SEO设置",
        detail: "详情设置"
      },
      selected: "basic",
      // 上述为tab选项
      mode: "twocolumn",
      // 表单一行几个
      form: {
        article_name: "",
        article_cate: "",
        article_label: "",
        article_detail: "",
        article_logo: "",
        article_introduce: "",
        seo_title: "",
        seo_keywords: "",
        seo_desc: ""
      },
      // 提交按钮的loading
      isLoading: false,
      validationRules: {
        rules: {},
        required: ["article_name"]
      }
    };
  },
  methods: {
    removeLogo() {
      this.form.article_logo = "";
    },
    chooseImg(e) {
      // 根据选项卡当前的位置来判断是要给哪个添加图片
      if (this.selected === "basic") {
        if (this.form.article_logo.length > 6) {
          this.$Message.error("够了~~~");
          return;
        }
        this.form.article_logo = e.src;
      }
      if (this.selected === "detail") {
        this.form.article_detail += `<img src=${e.src} style="max-width:100%">`;
      }
    },
    showImageChecek() {
      this.showDialog = true;
    },

    labelCurrentChange() {
      this.getlabelList();
    },
    async getCateList() {
      let res = await this.$get("/api/article/cate/list");
      if (res && res.code === 200) {
        this.cateOption.datas = res.data.list;
      } else {
        this.$Message.error("获取失败,请刷新重试");
      }
    },
    async getlabelList() {
      // 这里有个问题了。日 要是数据特别多。。怎么分页？？
      let res = await this.$get("/api/article/label/list", {
        limit: this.labelPagination.size,
        page: this.labelPagination.page
      });
      if (res && res.code === 200) {
        this.labelList = res.data.list;
        this.labelPagination.total = res.data.count;
      } else {
        this.$Message.error("获取失败,请刷新重试");
      }
    },
    // 考虑的问题：添加或者更新后。需不需要清空form。感觉跳转了应该不用
    async submit() {
      let validResult = this.$refs.form.valid();
      if (validResult.result) {
        // PHP 要每个都写。。日
        let res = await this.$post("/api/article", {
          article_name: this.form.article_name,
          article_introduce: this.form.article_introduce,
          article_cate: this.form.article_cate,
          article_label: this.form.article_label,
          article_logo: this.form.article_logo,
          article_detail: this.form.article_detail,
          seo_title: this.form.seo_title,
          seo_keywords: this.form.seo_keywords,
          seo_desc: this.form.seo_desc
        });
        if (res && res.code === 200) {
          this.$Message.success("添加成功");
          this.$router.push("/article");
        } else {
          this.$Message.error(res.message);
        }
      }
    },
    async update() {
      console.log(this.form);
      let validResult = this.$refs.form.valid();
      if (validResult.result) {
        let res = await this.$post(`/api/article/update/${this.id}`, {
          article_name: this.form.article_name,
          article_introduce: this.form.article_introduce,
          article_cate: this.form.article_cate,
          article_label: this.form.article_label,
          article_logo: this.form.article_logo,
          article_detail: this.form.article_detail,
          seo_title: this.form.seo_title,
          seo_keywords: this.form.seo_keywords,
          seo_desc: this.form.seo_desc
        });
        if (res && res.code === 200) {
          this.$Message.success("更新成功");
          this.$router.push("/article");
        } else {
          this.$Message.error(res.message);
        }
      }
    },
    async getarticle(id) {
      let res = await this.$get(`/api/article/find/${id}`);
      if (res && res.code === 200) {
        this.form = res.data;
      } else {
        this.$Message.error("获取失败~~");
      }
    },
    addCustomButtom(editorId) {
      let that = this;
      window.UE.registerUI(
        "选取图片",
        function(editor, uiName) {
          // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
          editor.registerCommand(uiName, {
            execCommand: function() {
              /*  editor.execCommand(
                "inserthtml",
                `<span>这是一段由自定义按钮添加的文字</span>`
              ); */
              // that.imageChooseDialog = true;
            }
          });

          // 创建一个 button
          var btn = new window.UE.ui.Button({
            // 按钮的名字
            name: uiName,
            // 提示
            title: "选择已上传的图片",
            // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
            cssRules:
              "background-image: url('../images/icons.png');background-position: -380px -120px",
            // 点击时执行的命令
            onclick: function() {
              // 这里可以不用执行命令，做你自己的操作也可
              // editor.execCommand(uiName);
              that.showDialog = true;
            }
          });
          editor.addListener("selectionchange", function() {
            var state = editor.queryCommandState(uiName);
            if (state === -1) {
              btn.setDisabled(true);
              btn.setChecked(false);
            } else {
              btn.setDisabled(false);
              btn.setChecked(state);
            }
          });
          return btn;
        },
        34,
        editorId
      );
    }
  },
  mounted() {
    if (this.id) {
      this.getarticle(this.id);
    }
    this.getCateList();
    this.getlabelList();
  },

  beforeDestroy() {}
};
</script>
<style lang="less" scoped>
.wapper {
  .item {
    .image {
      width: 100px !important;
      height: 50px;
    }
  }
}
.logoList {
  margin: 10px auto;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  .logo {
    margin-right: 5px;
    padding-top: 5px;
    height: 150px;
    text-align: center;
    i {
      display: block;
      font-size: 18px;
      color: #e11617;
    }
    img {
      margin: 0 10px;
      width: 100px;
      height: 100px;
    }
  }
}
</style>
